<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="155px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="标题" prop="name">
            <el-input v-model="formData.name" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="作者" prop="author">
            <el-input v-model="formData.author" placeholder="请输入作者" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="来源" prop="source">
            <el-input v-model="formData.source" placeholder="请输入来源" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关键字" prop="keywords">
            <el-input v-model="formData.keywords" placeholder="请输入关键字" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="场景分类">
            <el-select
              v-model="formData.nationSortName"
              placeholder="请选择场景分类"
              @change="nationSortNameChange"
            >
              <el-option
                v-for="item in nationSortNameListForm"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="领域分类">
            <el-select
              v-model="formData.readSortName"
              placeholder="请选择领域分类"
              @change="readSortNameChange"
            >
              <el-option
                v-for="item in readSortNameListForm"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="简介" prop="description">
            <el-input v-model="formData.description" placeholder="请输入简介" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="epub文件">
            <el-upload
              ref="upload"
              class="upload-demo"
              :http-request="saveFileUpload"
              multiple="true"
              :show-file-list="true"
              :accept="formatFile"
              :before-upload="beforeAvatarUpload"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="pdf文件">
            <el-upload
              ref="upload"
              class="upload-demo"
              :http-request="saveFileUpload"
              multiple="true"
              :show-file-list="true"
              :accept="formatFile"
              :before-upload="beforeAvatarUpload"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="false">
          <el-button type="primary">预览pdf</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="封面">
            <el-upload
              v-if="formData.coverSite == ''"
              ref="upload"
              class="upload-demo"
              :http-request="saveImageUpload"
              multiple="true"
              :show-file-list="true"
              :accept="formatPicture"
              :before-upload="beforeAvatarUpload"
            >
              <el-button type="primary">上传封面</el-button>
            </el-upload>
            <el-image
              v-if="formData.coverSite != ''"
              style="width: 100px; height: 100px"
              :src="buildImage()"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="4"
              fit="cover"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { FileFormat, FileSize, PictureFormat } from '@/utils/config'
import * as resourceApi from '@/api/resource'
import * as pictureApi from '@/api/picture'
import * as BookApi from '@/api/repository/book'
import { FormRules } from 'element-plus'
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'

//资源管理-图书弹窗
defineOptions({ name: 'RepositoryBookForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: '',
  keywords: '',
  source: '',
  nationSortId: '',
  nationSortName: '',
  readSortId: '',
  readSortName: '',
  fileFormat: '',
  epubSite: '',
  pdfSite: '',
  coverSite: '',
  author: '',
  description: ''
})
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const nationSortNameListForm = ref([]) // 国家分类名称列表
const readSortNameListForm = ref([]) // 特定场景阅读分类名称列表
const nationSortNameChange = (value: string) => {
  const data = nationSortNameListForm.value.find((item) => item.id === value)
  formData.value.nationSortId = value
  formData.value.nationSortName = data.categoryName
}
const readSortNameChange = (value: string) => {
  const data = readSortNameListForm.value.find((item) => item.id === value)
  formData.value.readSortId = value
  formData.value.readSortName = data.categoryName
}
/** 打开弹窗 */
const open = async (
  type: string,
  id?: number,
  nationSortNameList?: any,
  readSortNameList?: any
) => {
  nationSortNameListForm.value = nationSortNameList
  readSortNameListForm.value = readSortNameList
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BookApi.getBook(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BookApi.BookVO
    if (formType.value === 'create') {
      await BookApi.createBook(data)
      message.success(t('common.createSuccess'))
    } else {
      await BookApi.updateBook(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    keywords: '',
    source: '',
    nationSortId: '',
    nationSortName: '',
    readSortId: '',
    readSortName: '',
    fileFormat: '',
    epubSite: '',
    pdfSite: '',
    coverSite: '',
    author: '',
    description: ''
  }
  formRef.value?.resetFields()
}

const saveFileUpload = async (content) => {
  let form = new FormData()
  form.append('file', content.file)
  const data = await resourceApi.uploadFile(form)
  if (data.data.ext == 'epub') {
    formData.value.epubSite = data.data.previewUrl
  } else {
    formData.value.pdfSite = data.data.previewUrl
  }
  formData.value.fileFormat = data.data.ext
}

const saveImageUpload = async (content) => {
  let form = new FormData()
  form.append('file', content.file)
  const data = await pictureApi.upload(form)
  formData.value.coverSite = data.data.url
}
const buildImage = () => {
  return formData.value.coverSite
}
const formatFile = ref(FileFormat)
const formatPicture = ref(PictureFormat)
//上传前验证文件大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  let size = Number(FileSize)
  if (rawFile.size / 1024 / 1024 > Number(FileSize)) {
    ElMessage.error('file size can not exceed ' + size + 'MB!')
    return false
  }
  return true
}
</script>
